package com.camemax.controller.cep;

import com.camemax.pojo.LoginEvent;
import com.camemax.pojo.LoginFailedWarning;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.time.Duration;
import java.util.List;
import java.util.Map;


public class LoginFailedDetectCEP {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStream<String> fileDataStream = env.readTextFile(LoginFailedDetectCEP.class.getResource("/LoginLog.csv").getPath());
        KeyedStream<LoginEvent, Long> keyedStream = fileDataStream.map(line -> {
            String[] fields = line.split(",");
            return new LoginEvent(
                    Long.valueOf(fields[0]),
                    fields[1],
                    fields[2],
                    Long.parseLong(fields[3])
            );
        }).assignTimestampsAndWatermarks(WatermarkStrategy.<LoginEvent>forBoundedOutOfOrderness(Duration.ofSeconds(10))
                .withTimestampAssigner((SerializableTimestampAssigner<LoginEvent>) (pojo, defaultTime) -> pojo.getLoginDate() * 1000L))
                .keyBy(LoginEvent::getUserId);

        Pattern<LoginEvent, LoginEvent> patternRule = Pattern
                .<LoginEvent>begin("first-failed").where(new SimpleCondition<LoginEvent>() {
                    @Override
                    public boolean filter(LoginEvent value) throws Exception {
                        return "fail".equals(value.getLoginStatus());
                    }})
                .next("second-failed").where(new SimpleCondition<LoginEvent>() {
                    @Override
                    public boolean filter(LoginEvent value) throws Exception {
                        return "fail".equals(value.getLoginStatus());
                    }})
                .within(Time.seconds(2));

        PatternStream<LoginEvent> patternStream = CEP.pattern(keyedStream, patternRule);

        patternStream.select(new PatternSelectFunction<LoginEvent, LoginFailedWarning>() {
            @Override
            public LoginFailedWarning select(Map<String, List<LoginEvent>> map) throws Exception {
                LoginEvent firstFail = map.get("first-failed").iterator().next();
                LoginEvent secondFail = map.get("second-failed").get(0);
                return new LoginFailedWarning(
                        firstFail.getUserId()
                        , "Login Failed 2 times in 2 seconds."
                        , firstFail.getLoginDate().toString()
                        , secondFail.getLoginDate().toString()
                );
            }
        }).print();


        env.execute();
    }
}
